<?php
namespace Controllers;

class managerController extends Controller
{
    public function userList()
    {
        // $res = $this->container['db']->select($this->userTable.'(user)', [
        //     '[><]'.$this->roleUserTable.'(roleUser)' => [
        //         'id' => 'user_id'
        //     ]
        // ], [
        //     'user.id',
        //     'user.uid',
        //     'user.username',
        //     'user.status',
        //     'user.login_time',
        //     'user.login_ip',
        //     'roleUser.role_id(position)'
        // ], [
        //     'is_delete' => '0',
        //     'ORDER' => 'user.id'
        // ]);
        $this->checkAccess($this->getUserId(), '5');
        $sql = "SELECT `user`.`id`,`user`.`uid`,`user`.`username`,`user`.`status`,
                `user`.`login_time`,`user`.`login_ip`,GROUP_CONCAT(`roleUser`.`role_id` SEPARATOR '') AS `position` 
                FROM `user` AS `user` 
                INNER JOIN `role_user` AS `roleUser` ON `user`.`id` = `roleUser`.`user_id` 
                WHERE `is_delete` = '0' GROUP BY `user`.`id`";

        $res = $this->container['db']->query($sql)->fetchAll(\PDO::FETCH_CLASS);       
        // var_dump($this->container['db']->log());
        foreach ($res as $key => $value) {
            $res[$key] = self::object_array($value);
            // 去除职位中重复的字符,可包装成函数
            $position = array();
            for($i = 0; $i < strlen($res[$key]['position']); $i++)
            {
                $position[] = $res[$key]['position'][$i];
            }
            $position = array_unique($position);
            $res[$key]['position'] = '';
            // var_dump($position);
            for($j = 0; $j < count($position); $j++)
            {
                $res[$key]['position'] .= $position[$j];
            }
        }
        if(!$this->container['db']->error()[1])
        {
            return json_encode($res);
        }
        else
        {
            return self::jsonFail('获取失败');
        }
    }



    // 角色列表
    public function roleList()
    {
        $this->checkAccess($this->getUserId(), '5');
        $res = $this->container['db']->select($this->roleTable, [
            'id',
            'name',
            'remark'
        ]);
        return ($this->container['db']->error()[1])?(self::jsonFail('数据库错误')):(json_encode($res));
    }

    public function updateRole()
    {
        $this->checkAccess($this->getUserId(), '5');
        $data = $_POST;
        if($data['id'] && $data['role_id'])
        {
            //检查数据库中是否有数据
            $res = $this->container['db']->select($this->roleUserTable, '*', [
                'user_id' => $data['id']
            ]);
            if(!$res)
            {
                return self::jsonFail('更新失败');
            }
            else
            {
                $status = $this->container['db']->action(function($database) use($data){
                    $roles = $this->container['db']->select($this->roleTable, 'id');
                    $row = $database->delete($this->roleUserTable, [
                       'user_id' =>  $data['id']
                    ]);
                    if(!$row->rowCount()) return false;
                    $position = array();
                    for($i = 0; $i < strlen($data['role_id']); $i++)
                    {
                        $position[] = $data['role_id'][$i];
                    }
                    // 权限数组
                    $position = array_unique($position);
                    foreach ($roles as $key => $value)
                    {
                        foreach ($position as $key1 => $role) 
                        {
                            if($role == $value)
                            {
                                $database->insert($this->roleUserTable, [
                                    'role_id' => $role,
                                    'user_id' => $data['id']
                                ]);
                                if($database->error()[1]) return false;
                            }
                        }
                    }
                    return true;
                });
                if($status)
                {
                    return self::jsonSuccess('更新成功');
                }
                else
                {
                    return self::jsonFail('更新失败');
                }      
            }    
        }
        else
        {
            return self::jsonFail('请输入用户id或者角色id');
        }
    }

    public function updatePw()
    {
        $this->checkAccess($this->getUserId(), '5');
        $data = $_POST;
        if($data['id'] && $data['new_password'])
        {
            //检查数据库中是否有数据
            $res = $this->container['db']->select($this->userTable, '*', [
                'uid' => $data['id']
            ]);
            if(!$res)
            {
                return self::jsonFail('更新失败');
            }
            else
            {
                $this->container['db']->update($this->userTable, [
                    'password' => $data['new_password']
                ], [
                    'uid' => $data['id']
                ]);
                if(!$this->container['db']->error()[1])
                {
                    return self::jsonSuccess('更新成功');
                }
                else
                {
                    return self::jsonFail('更新失败');
                }
            }
        }
        else
        {
            return self::jsonFail('请输入用户id或者用户密码');
        }
    }

    public function changePw()
    {
        $this->checkAccess($this->getUserId(), '5');        
        $data = $_POST;
        if($data['old_password'])
        {
            if($data['new_password'])
            {
                $res = $this->container['db']->select($this->userTable, 'id', [
                    'password' => $data['old_password'],
                    'uid' => $this->getUserUid()
                ]);
                if(!$res)
                {
                    return self::jsonFail('更新失败');
                }
                else
                {
                    $this->container['db']->update($this->userTable, [
                        'password' => $data['new_password']
                    ], [
                        'uid' => $this->getUserUid(),
                        'password' => $data['old_password']
                    ]);
                    if(!$this->container['db']->error()[1])
                    {
                        return self::jsonSuccess('更新成功');
                    }
                    else
                    {
                        return self::jsonFail('更新失败');
                    }
                }
            }
            else
            {
                return self::jsonFail("请输入新密码");
            }
        }
        else
        {
            return self::jsonFail("请输入旧密码");
        }
    }

    public function userAdd()
    {
        $this->checkAccess($this->getUserId(), '5');        
        if($_POST['uid'])
        {
            if($_POST['name'])
            {
                if($_POST['password'])
                {
                    if($_POST['role_id'])
                    {
                        $res = $this->container['db']->action(function($database) {
                            $row = $database->insert($this->userTable, [
                                                        'id' => '',
                                                        'uid' => $_POST['uid'],
                                                        'username' => $_POST['name'],
                                                        'password' => $_POST['password']
                                                    ]);
                            if($row->rowCount())
                            {
                                $id = $database->id();
                                $roles = $database->select($this->roleTable, 'id');
                                foreach ($roles as $key => $value) 
                                {
                                    $position = array();
                                    for($i = 0; $i < strlen($_POST['role_id']); $i++)
                                    {
                                        $position[] = $_POST['role_id'][$i];
                                    }
                                    $position = array_unique($position);
                                    foreach ($position as $key1 => $role) 
                                    {
                                        if($role == $value)
                                        {
                                            $row1 = $database->insert($this->roleUserTable, [
                                                'role_id' => $role,
                                                'user_id' => $id
                                            ]);       
                                            if(!$row1->rowCount())
                                            {
                                                return false; 
                                            }
                                        }
                                    }
                                }
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        });
                        if($res)
                        {
                            return self::jsonSuccess('增加成功');
                        }
                        else
                        {
                            return self::jsonFail('增加失败');
                        }
                    }
                    else
                    {
                        return self::jsonFail('请输入角色id');
                    }
                }
                else
                {
                    return self::jsonFail('请输入密码');
                }
            }
            else
            {
                return self::jsonFail('请输入名字');
            }
        }
        else
        {
            return self::jsonFail('请输入工号');
        }
    }

    public function userDel()
    {
        $this->checkAccess($this->getUserId(), '5');        
        if($_POST['id'] == $this->getUserId()) return self::jsonFail('不能删除自己');
        if($_POST['id'])
        {
            $row = $this->container['db']->update($this->userTable, [
                'is_delete' => 1
            ], [
                'id' => $_POST['id']
            ]);
            if($row->rowCount())
            {
                return self::jsonSuccess('删除成功');
            }
            else
            {
                return self::jsonFail('删除失败');
            }
        }
        else
        {
            return self::jsonFail('请输入id');
        }
    }

    public function userDisable()
    {
        $this->checkAccess($this->getUserId(), '5');   
        if($_POST['id'] == $this->getUserId()) return self::jsonFail('不能禁用自己');
        if($_POST['id'])
        {
            $this->container['db']->update($this->userTable, [
                'status' => 0
            ], [
                'id' => $_POST['id']
            ]);
            if(!$this->container['db']->error()[1])
            {
                return self::jsonSuccess('禁用成功');
            }
            else
            {
                return self::jsonFail('禁用失败');
            }
        }
        else
        {
            return self::jsonFail('请输入id');
        }
    }

    public function userEnable()
    {
        $this->checkAccess($this->getUserId(), '5');        
        if($_POST['id'])
        {
            $this->container['db']->update($this->userTable, [
                'status' => 1
            ], [
                'id' => $_POST['id']
            ]);
            if(!$this->container['db']->error()[1])
            {
                return self::jsonSuccess('禁用成功');
            }
            else
            {
                return self::jsonFail('禁用失败');
            }
        }
        else
        {
            return self::jsonFail('请输入id');
        }
    }


    public function updatePhone()
    {
        $user_id = $this->getUserId();
        if($_POST['phone'])
        {
            $data = $this->container['db']->update($this->userTable, [
                'telnum' => $_POST['phone']
            ], [
                'id' => $user_id
            ]);
            return ($data->rowCount())?(self::jsonSuccess('更新成功')):(self::jsonFail('更新失败'));
        }
        else 
        {
            return self::jsonFail('电话号码不能为空');
        }
    }

    public function ipAndTime()
    {
        $user_id = $this->getUserId();
        $res =  $this->container['db']->select($this->userTable, [
            'login_time',
            'login_ip'
        ], [
            'id' => $user_id
        ]);
        return ($this->container['db']->error()[1])?(self::jsonFail('获取失败')):(json_encode($res));
    }

    public function test()
    {
        $data = $this->container['db']->insert($this->roleProjectTable, [
            'project_id' => '1',
            'user_id' => '1'
        ]);
        echo $data->rowCount();
	}

    // 选出对应角色的用户
    public function showRoleUser(int $role_id)
    {
        $res = $this->container['db']->select($this->roleUserTable.'(role)', [
            '[><]'.$this->userTable.'(user)' => [
                'role.user_id' => 'id'
            ]
        ], [
            'user.id',
            'user.username'
        ],
        [
            'role.role_id' => $role_id
        ]);
        // var_dump($this->container['db']->log());
        return ($this->container['db']->error()[1])?(self::jsonFail('数据库出错')):(json_encode($res));
    }

    public function depAudit()
    {
        return $this->showRoleUser(2);
    }

    public function centerAudit()
    {
        return $this->showRoleUser(3);
    }
}

